<template>
  <view class="container">
    <view class="header">
      <view class="title">商品评价</view>
      <view class="subtitle">请对购买的商品进行评价</view>
    </view>
    
    <view class="product-info" v-if="product">
      <image :src="product.image || '/static/images/default-category.png'" class="product-image" mode="aspectFill"></image>
      <view class="product-detail">
        <text class="product-name">{{ product.name }}</text>
        <text class="product-specs">{{ specs }}</text>
      </view>
    </view>
    
    <view class="rating-section">
      <text class="rating-title">总体评分</text>
      <view class="star-rating">
        <text 
          v-for="i in 5" 
          :key="i" 
          class="star" 
          :class="{ 'active': i <= rating }"
          @click="setRating(i)"
        >★</text>
      </view>
    </view>
    
    <view class="review-section">
      <textarea 
        class="review-content" 
        placeholder="请分享您的购买体验，对商品的评价、使用感受等（最少5个字）" 
        v-model="content"
        maxlength="500"
      ></textarea>
      <view class="word-count">{{ content.length }}/500</view>
    </view>
    
    <view class="upload-section">
      <text class="upload-title">添加图片（最多6张）</text>
      <view class="image-upload-grid">
        <view 
          v-for="(image, index) in images" 
          :key="index" 
          class="image-item"
        >
          <image :src="image" class="preview-image" mode="aspectFill"></image>
          <text class="delete-icon" @click="removeImage(index)">×</text>
        </view>
        <view class="image-add" @click="addImage" v-if="images.length < 6">
          <text class="add-icon">+</text>
        </view>
      </view>
      
      <!-- 上传进度条，仅在上传过程中显示 -->
      <view class="upload-progress-container" v-if="uploadProgress > 0 && uploadProgress < 100">
        <view class="upload-progress">
          <view class="upload-progress-bar" :style="{ width: uploadProgress + '%' }"></view>
        </view>
        <view class="upload-status">上传中 {{ uploadProgress }}%</view>
      </view>
    </view>
    
    <view class="checkbox-section">
      <checkbox :checked="anonymous" color="#ff6700" @click="toggleAnonymous"></checkbox>
      <text class="checkbox-label">匿名评价</text>
    </view>
    
    <view class="button-section">
      <button class="submit-btn" @click="submitReview" :disabled="!canSubmit || loading">
        {{ loading ? '提交中...' : '提交评价' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { reviewApi } from '../../api/review.js';
import { commonApi } from '../../api/common.js';

// 数据定义
const orderId = ref(null);
const orderItemId = ref(null);
const reviewId = ref(null);  // 如果是编辑评价，则需要此ID
const product = ref(null);
const specs = ref('');
const rating = ref(5);  // 默认5星
const content = ref('');
const images = ref([]);
const originalImages = ref([]); // 存储原始图片，用于编辑评价时
const anonymous = ref(false);
const loading = ref(false);
const uploadProgress = ref(0); // 上传进度

// 计算属性
const canSubmit = computed(() => {
  return rating.value > 0 && content.value.length >= 5;
});

// 接收页面参数
onLoad((options) => {
  if (options.orderId) {
    orderId.value = options.orderId;
  }
  if (options.itemId) {
    orderItemId.value = options.itemId;
  }
  if (options.reviewId) {
    reviewId.value = options.reviewId;
    // 如果有reviewId，说明是编辑评价，加载评价详情
    loadReviewDetails();
  }
  if (options.productInfo) {
    try {
      product.value = JSON.parse(decodeURIComponent(options.productInfo));
    } catch (e) {
      console.error('解析商品信息失败', e);
    }
  }
  if (options.specs) {
    specs.value = decodeURIComponent(options.specs);
  }
});

// 设置评分
const setRating = (value) => {
  rating.value = value;
};

// 添加图片
const addImage = () => {
  if (images.value.length >= 6) {
    uni.showToast({
      title: '最多只能上传6张图片',
      icon: 'none'
    });
    return;
  }
  
  // 设置图片大小限制为2MB
  const MAX_IMAGE_SIZE = 2 * 1024 * 1024; // 2MB
  
  uni.chooseImage({
    count: 6 - images.value.length,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFiles = res.tempFiles || res.tempFilePaths.map((path, i) => ({
        path,
        size: res.tempFiles ? res.tempFiles[i].size : 0
      }));
      
      // 检查每张图片大小
      const validFiles = [];
      let hasOversize = false;
      let checked = 0;
      
      tempFiles.forEach(file => {
        // 如果有size字段直接判断，没有则用uni.getFileInfo
        if (file.size && file.size > 0) {
          if (file.size <= MAX_IMAGE_SIZE) {
            validFiles.push(file.path);
          } else {
            hasOversize = true;
          }
          checked++;
          if (checked === tempFiles.length) {
            handleChooseResult(validFiles, hasOversize);
          }
        } else {
          uni.getFileInfo({
            filePath: file.path,
            success: (info) => {
              if (info.size <= MAX_IMAGE_SIZE) {
                validFiles.push(file.path);
              } else {
                hasOversize = true;
              }
              checked++;
              if (checked === tempFiles.length) {
                handleChooseResult(validFiles, hasOversize);
              }
            },
            fail: () => {
              checked++;
              if (checked === tempFiles.length) {
                handleChooseResult(validFiles, hasOversize);
              }
            }
          });
        }
      });
    },
    fail: (err) => {
      console.error('选择图片失败', err);
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      });
    }
  });
};

// 处理选择图片结果
const handleChooseResult = (validFiles, hasOversize) => {
  if (hasOversize) {
    uni.showToast({
      title: '有图片超过2MB，已自动过滤',
      icon: 'none',
      duration: 2000
    });
  }
  
  // 将有效的图片添加到预览数组
  if (validFiles.length > 0) {
    images.value.push(...validFiles);
  }
};

// 删除图片
const removeImage = (index) => {
  images.value.splice(index, 1);
};

// 切换匿名评价
const toggleAnonymous = () => {
  anonymous.value = !anonymous.value;
};

// 上传单个图片并显示进度
const uploadImagesWithProgress = async (imageList) => {
  if (!imageList || imageList.length === 0) {
    return [];
  }
  
  const total = imageList.length;
  const uploadedUrls = [];
  
  try {
    // 开始上传图片
    for (let i = 0; i < total; i++) {
      // 更新进度
      uploadProgress.value = Math.floor((i / total) * 100);
      
      try {
        // 上传单个图片，一次只上传一张，避免并发问题
        const url = await commonApi.uploadFile(imageList[i]);
        uploadedUrls.push(url);
        
        // 打印调试信息
        console.log(`图片 ${i + 1}/${total} 上传成功:`, url);
        
        // 每上传一张图片等待一小段时间
        if (i < total - 1) {
          await new Promise(resolve => setTimeout(resolve, 300));
        }
      } catch (error) {
        console.error(`图片 ${i + 1}/${total} 上传失败:`, error);
        uni.showToast({
          title: `第${i + 1}张图片上传失败`,
          icon: 'none',
          duration: 2000
        });
      }
    }
  } catch (error) {
    console.error('批量上传图片过程中出错:', error);
  } finally {
    // 完成上传
    uploadProgress.value = 100;
  }
  
  return uploadedUrls;
};

// 提交评价
const submitReview = async () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: '请填写评价内容（最少5个字）',
      icon: 'none'
    });
    return;
  }
  
  if (loading.value) return;
  loading.value = true;
  
  try {
    let uploadedImageUrls = [];
    
    // 如果有选择图片，则先上传图片
    if (images.value.length > 0) {
      uni.showLoading({
        title: '上传图片中...',
        mask: true
      });
      
      uploadedImageUrls = await uploadImagesWithProgress(images.value);
      
      uni.hideLoading();
      
      if (uploadedImageUrls.length === 0 && images.value.length > 0) {
        throw new Error('图片上传失败，请重试');
      }
      
      if (uploadedImageUrls.length < images.value.length) {
        uni.showModal({
          title: '提示',
          content: `部分图片上传失败，是否继续提交评价？已成功上传 ${uploadedImageUrls.length}/${images.value.length} 张`,
          success: (res) => {
            if (!res.confirm) {
              loading.value = false;
              return;
            }
          }
        });
      }
    }
    
    // 图片上传完成后，准备提交评价数据
    uni.showLoading({
      title: '提交评价...',
      mask: true
    });
    
    // 将上传成功的图片URL转换为JSON字符串
    const imagesJson = uploadedImageUrls.length > 0 ? JSON.stringify(uploadedImageUrls) : '';
    
    // 构建评价数据
    const reviewData = {
      orderId: orderId.value,
      productId: product.value?.id,
      skuId: orderItemId.value, 
      rating: rating.value,
      comment: content.value,
      images: imagesJson,
      isAnonymous: anonymous.value ? 1 : 0
    };
    
    console.log('提交评价数据:', reviewData);
    
    // 提交评价
    const res = await reviewApi.addReview(reviewData);
    
    if (res.code === 200) {
      uni.showToast({
        title: '评价提交成功',
        icon: 'success'
      });
      
      // 延迟后返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      throw new Error(res.msg || '评价提交失败');
    }
  } catch (error) {
    console.error('提交评价失败:', error);
    uni.showToast({
      title: error.message || '提交失败，请稍后再试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
    loading.value = false;
  }
};

// 加载评价详情
const loadReviewDetails = async () => {
  loading.value = true;
  try {
    const res = await reviewApi.getReviewById(reviewId.value);
    
    if (res.code === 200 && res.data) {
      const review = res.data;
      
      // 填充表单数据
      rating.value = review.rating || 5;
      content.value = review.comment || ''; // 使用comment字段
      anonymous.value = review.isAnonymous === 1;
      
      // 处理图片，支持JSON字符串格式
      if (review.images) {
        let imageArray = [];
        
        if (typeof review.images === 'string') {
          try {
            // 尝试解析JSON字符串
            imageArray = JSON.parse(review.images);
          } catch (e) {
            console.error('解析图片数据失败:', e);
          }
        } else if (Array.isArray(review.images)) {
          imageArray = review.images;
        }
        
        if (Array.isArray(imageArray) && imageArray.length > 0) {
          images.value = [...imageArray];
          originalImages.value = [...imageArray];
        }
      }
    } else {
      uni.showToast({
        title: '获取评价详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('加载评价详情失败:', error);
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};
</script>

<style>
.container {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.header {
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 28rpx;
  color: #666;
}

.product-info {
  display: flex;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  background-color: #f5f5f5;
}

.product-detail {
  flex: 1;
  padding-left: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.product-specs {
  font-size: 26rpx;
  color: #999;
  background-color: #f8f8f8;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
  display: inline-block;
}

.rating-section {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
}

.rating-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.star-rating {
  display: flex;
  justify-content: center;
}

.star {
  font-size: 60rpx;
  color: #ddd;
  margin: 0 10rpx;
}

.star.active {
  color: #ff6700;
}

.review-section {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  position: relative;
}

.review-content {
  width: 100%;
  height: 240rpx;
  font-size: 28rpx;
  padding: 10rpx;
  box-sizing: border-box;
  background-color: #fff;
}

.word-count {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  font-size: 24rpx;
  color: #999;
}

.upload-section {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
}

.upload-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.image-upload-grid {
  display: flex;
  flex-wrap: wrap;
}

.image-item {
  width: 150rpx;
  height: 150rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.delete-icon {
  position: absolute;
  top: -15rpx;
  right: -15rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

.image-add {
  width: 150rpx;
  height: 150rpx;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  border: 1rpx dashed #ddd;
}

.add-icon {
  font-size: 60rpx;
  color: #999;
}

.checkbox-section {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
}

.checkbox-label {
  font-size: 28rpx;
  color: #333;
  margin-left: 10rpx;
}

.button-section {
  padding: 20rpx 0;
}

.submit-btn {
  width: 100%;
  background-color: #ff6700;
  color: white;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 45rpx;
  padding: 25rpx 0;
  border: none;
}

.submit-btn:disabled {
  background-color: #ccc;
}

/* 上传进度条样式 */
.upload-progress {
  margin-top: 20rpx;
  background-color: #f1f1f1;
  border-radius: 10rpx;
  height: 10rpx;
  width: 100%;
  margin-bottom: 10rpx;
}

.upload-progress-bar {
  background-color: #ff6700;
  height: 100%;
  border-radius: 10rpx;
  transition: width 0.3s;
}

.upload-status {
  font-size: 24rpx;
  color: #666;
  text-align: center;
  margin-bottom: 20rpx;
}

.upload-progress-container {
  margin-top: 20rpx;
  padding: 10rpx;
  background-color: #fff;
  border-radius: 10rpx;
  box-sizing: border-box;
}
</style> 